package com.crm.service.system.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.domain.dto.QueryDictType;
import com.crm.domain.entity.DictType;
import com.crm.mapper.DictTypeMapper;
import com.crm.service.system.DictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @author Xanny
 */
@Service
@RequiredArgsConstructor
public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, DictType> implements DictTypeService {

    private final DictTypeMapper dictTypeMapper;
    /**
     * 分页查询所有的dict_type
     * @param queryDictType
     * @return
     */
    @Override
    public Page<DictType> queryAll(QueryDictType queryDictType) {
        //1.设置分页参数
        /*
            请求list和请求分页都是同一个接口 如果不对空值进行初始化 会有空指针异常。
            解决方式:手动设置初始值 但ObjectUtil.isEmpty会把null也判断为对象 需要取值或者queryDictType==null
         */
        Page<DictType> page =ObjectUtil.isEmpty(queryDictType.getPageNum())?Page.of(1, 10):Page.of(queryDictType.getPageNum(), queryDictType.getPageSize());

        //2.调用Mapper查询数据
        //2.1构建查询条件
        Map<String, Object> params = queryDictType.getParams();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate beginTime =ObjectUtil.isEmpty(params)?null:(LocalDate.parse((String)params.get("beginTime"), formatter));
        LocalDate endTime =ObjectUtil.isEmpty(params)?null:(LocalDate.parse((String)params.get("endTime"), formatter));

        LambdaQueryWrapper<DictType> wrapper = Wrappers.<DictType>lambdaQuery()
                .like(ObjectUtil.isNotEmpty(queryDictType.getDictName()),DictType::getDictName, queryDictType.getDictName())
                .like(ObjectUtil.isNotEmpty(queryDictType.getDictType()),DictType::getDictType, queryDictType.getDictType())
                .eq(ObjectUtil.isNotEmpty(queryDictType.getStatus()),DictType::getStatus, queryDictType.getStatus())
                .between(ObjectUtil.isNotEmpty(beginTime)&&ObjectUtil.isNotEmpty(endTime)
                        ,DictType::getCreateTime, beginTime, endTime);

        //2.2用m-plus查询
        Page<DictType> dictTypePage = page(page, wrapper);

        return dictTypePage;
    }
}
